package com.xwltz.common.phone.algorithm;

import com.xwltz.common.phone.base.PhoneBase;
import com.xwltz.common.phone.base.PhoneModel;

import java.util.Optional;

/**
 * @description ProspectBinarySearchAlgorithm
 * @information on version 1.0 be created by @xwltz at 2021/11/08 15:46
 */

@SuppressWarnings("DuplicatedCode")
public class ProspectBinarySearchAlgorithm extends PhoneBase {
	@Override
	public Optional<PhoneModel> getInfo(String phoneNumber) {
		if (checkInvalidPhoneNumber(phoneNumber)) return Optional.empty();
		int attributionIdentity = checkPhoneNumberIsNumber(phoneNumber);
		if (attributionIdentity == 0) return Optional.empty();

		int left = indicesStartOffset;
		int right = indicesEndOffset;
		int attributionIdentityPrefix = attributionIdentity / 100_000;
		int mid = indicesStartOffset + ((indicesEndOffset - indicesStartOffset) / 7 * (attributionIdentityPrefix - 13));
		mid = alignPosition(mid);
		while (mid >= left && mid <= right) {
			if (mid == right) {
				return Optional.empty();
			}
			int compare = compare(mid, attributionIdentity, originalByteBuffer);

			if (compare == 0) {
				return extract(phoneNumber, mid, originalByteBuffer);
			} else if (mid == left) {
				return Optional.empty();
			} else if (compare > 0) {
				int tempMid = (mid + left) / 2;
				right = mid;
				mid = alignPosition(tempMid);
			} else {
				int tempMid = (mid + right) / 2;
				left = mid;
				mid = alignPosition(tempMid);
			}
		}
		return Optional.empty();
	}
}
